﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System.Data;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Writes to server.
        /// </summary>
        /// <param name="useTemporaryTable">(Optional) true to use temporary table.</param>
        public void WriteToServer(bool useTemporaryTable = true)
        {
            string originalDestinationName = SqlBulkCopy.DestinationTableName;

            // Only bulk insert doesn't use temporary table. 
            if (useTemporaryTable)
            {
                SqlBulkCopy.DestinationTableName = string.Concat("[", TemporaryTableName + "]");
            }

            if (InternalDataSource is DataTable)
            {
                if (DataRowState.HasValue)
                {
                    SqlBulkCopy.WriteToServer(InternalDataSource as DataTable, DataRowState.Value);
                }
                else
                {
                    SqlBulkCopy.WriteToServer(InternalDataSource as DataTable);
                }
            }
            else if (InternalDataSource is DataRow[])
            {
                SqlBulkCopy.WriteToServer(InternalDataSource as DataRow[]);
            }
            else if (InternalDataSource is IDataReader)
            {
                SqlBulkCopy.WriteToServer(InternalDataSource as IDataReader);
            }

            if (useTemporaryTable)
            {
                SqlBulkCopy.DestinationTableName = originalDestinationName;
            }
        }
    }
}